// pages/device/state/state.js

// 参数页面

var app = getApp()
var cmd = require('../../../command/command.js')
var bluetooth = require('../../../command/bluetooth.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    objectArray: [{
        name: "当前转速",
        value: 0,
        unit: "rpm",
        id: ""
      },
      {
        name: "当前功率",
        value: 0.00,
        unit: "w"
      },
      {
        name: "当前运行时间",
        value: "0:0:0",
        unit: ""
      },
      {
        name: "总运行时间",
        value: "0小时31分",
        unit: ""
      },
      {
        name: "自启电压",
        value: null,
        unit: "V"
      },
      {
        name: "启动加浓",
        value: null,
        unit: ""
      },
      {
        name: "输出电压",
        value: null,
        unit: "V"
      },
      {
        name: "稳定性调节",
        value: null,
        unit: ""
      },
      {
        name: "当前工作模式",
        value: "标准",
        unit: ""
      },
      {
        name: "控制器序列号",
        value: null,
        unit: ""
      },
      {
        name: "产品型号",
        value: null,
        unit: ""
      },
      {
        name: "二维码",
        value: null,
        unit: ""
      },
      {
        name: "面板开关状态",
        value: null,
        unit: ""
      },
      {
        name: "发电机运行状态",
        value: null,
        unit: ""
      },
      {
        name: "激活日期",
        value: null,
        unit: ""
      },
      {
        name: "激活地址",
        value: null,
        unit: ""
      },
      {
        name: "激活用户",
        value: null,
        unit: ""
      },
      {
        name: "预约启停",
        value: null,
        unit: ""
      },
      {
        name: "预约启动时间",
        value: null,
        unit: ""
      },
      {
        name: "预约停止时间",
        value: null,
        unit: ""
      },
      {
        name: "控制器温度",
        value: null,
        unit: ""
      },
      {
        name: "发动机温度",
        value: null,
        unit: ""
      },
    ],
    // 下拉框
    list: [{
        value: 'label_1',
        label: '设备状态',
        icon: 'pin'
      },
      {
        value: 'label_2',
        label: '设备参数',
        icon: 'app'
      },
      {
        value: 'label_3',
        label: '参数页面',
        icon: 'chat'
      },
    ],
    speed: 0,
    valtage: 0, //电压
    current: 0, //电流
    runHour: 0,
    runMin: 0,
    totalTimeHour: 0,
    totalTimeMin: 0,
    startValtage: 0,
    plusContral: 0,
    outValtage: 0, //输出电压
    adjust: 0, //稳定性调节
    machineMode: "--", //当前工作模式
    machineVersion: "--",
    reservation: "未启用",
    startTimeHour: 0,
    startTimeMin: 0,
    stopTimeHour: 0,
    stopTimeMin: 0,
    machineTemperature: 0, //发动机温度
    controllerTemperature: 0, //控制器温度
    value: 'label_3',
  },

  //状态信息相关数据
  sendStateArry: [
    ("machineSpeed"),
    ("controllerOutCurrent"),
    ("machineWorkState"),
    ("machineErrorState"),
    ("machineTemperature"),
    ("controllerTemperature"),
    // ("oilLevel"),
    ("timeHour"),
    ("timeMin"),
    ("controllerOutVoltage"),
    ("controllerOutVoltageR"),
    ("chargeCurrentR"),
    ("autoStartVoltageR"),
    // ("autoStopCurrentR"),
    // ("autoStopVoltageR"),
    // ("stopTimeHourR"),
    // ("stopTimeMinR"),
    // ("stopTimeSecR"),

    ("appVersion"),
    ("machineVersion"),
    ("machineMode"),
    ("startTimeHour"),
    ("startTimeMin"),
    ("plusContral"),
    ("adjust"),
    ("totalTimeHour"),
    ("totalTimeMin"),
    "machineTemperature", //发动机温度
    "controllerTemperature", //控制器温度
  ],
  intevalId: null,
  updateId: null,

  goSend() {
    if (!this.isCurPage())
      return
    if (app.globalData.connected) {
      console.log("sending...")
      for (var k = 0; k < this.sendStateArry.length; k++) {
        bluetooth.send(cmd.getCommandByName(this.sendStateArry[k]))
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("onLoad")

    //定时发送数据
    this.intevalId = setInterval(() => {
      this.goSend()
    }, 2000);

    cmd.resetRecDataState()
    this.updateData()

    this.updateId = setInterval(() => {
      this.updateData()
    }, 50);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log("参数页面OnShow")
    this.goSend()
    this.updateData()
    this.setData({
      value: 'label_3',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log("state.js onHide()")
  },


  onChange(e) {
    this.setData({
      value: e.detail.value,
    });
    if (e.detail.value == "label_1") {
          console.log("current-Page-Length:",getCurrentPages().length)
          if (getCurrentPages().length > 8)
          {
            wx.reLaunch({
              url: '../home/home',
            })
            
          }
          else{
            wx.navigateTo({
              url: '../home/home',
            })
          }
    } else if (e.detail.value == "label_2") {
          console.log("current-Page-Length:",getCurrentPages().length)
          if (getCurrentPages().length > 8)
          {
            wx.reLaunch({
              url: '../writesetting/writesetting',
            })
            
          }
          else{
            wx.navigateTo({
              url: '../writesetting/writesetting',
            })
          }
    } else {
      // wx.navigateTo({
      //   url: '../state/state',
      // })
    }
    // setTimeout(()=>{
    //   // this.setData({
    //   //   value: "label_1",
    //   // })
    // }, 1000);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log('pages/device/state/state onUnload')
    clearInterval(this.intevalId)
    clearInterval(this.updateId);
  },

  isCurPage() {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    return currentPage.route === 'pages/device/state/state';
  },

  /**
   * 更新页面数据
   */
  updateData() {
    if (!this.isCurPage())
      return

    if (!app.globalData.connected) {
      return
    }

    // console.log('-------------------->updateData()')
    // console.log(cmd.recDataStruct)

    Object.keys(cmd.recDataStruct).forEach(e => {
      if (cmd.recDataStruct[e][1] == true) {
        cmd.recDataStruct[e][1] = false
        var value = cmd.recDataStruct[e][0]
        console.log(e, cmd.recDataStruct[e][0], cmd.recDataStruct[e][1])
        switch (e) {
          case "0000":
            this.data.speed = value
            break
          case "0001":
            this.data.current = value
            break
          case "0002": //发动机工作状态 停用 手动 自动
            break
            // case "0003": //设备故障状态
            // break
          case "0004":
            this.data.machineTemperature = value
            break
          case "0005":
            this.data.controllerTemperature = value
            break
            // case "0006": break
          case "0007":
            this.data.runHour = value
            break
          case "0008":
            this.data.runMin = value
            break
          case "0009": // 瞬时电压
            this.data.valtage = value
            break
          case "000A": // 设置电压
            this.data.outValtage = value
            break
            // case "000B": break
          case "000C":
            this.data.startValtage = value
            break
            // case "000D": break
            // case "000E": break
          case "000F":
            this.data.stopTimeHour = value
            break
          case "0010":
            this.data.stopTimeMin = value
            break
            // case "0011": break
            // case "0012": break
            // case "0013": break
            // case "0014": break
            // case "0015": break
            // case "0016": break
            // case "0017": break
          case "0018":
            break
          case "0019":
            this.data.machineVersion = value;
            break
          case "001A": //模式控制
            switch (value) {
              case 1:
                this.data.machineMode = "节能模式";
                break;
              case 2:
                this.data.machineMode = "标准模式";
                break;
              case 3:
                this.data.machineMode = "充电模式";
                break;
              case 4:
                this.data.machineMode = "自定义";
                break;
            }
            break
          case "001E":
            this.data.startTimeHour = value
            break
          case "001F":
            this.data.startTimeMin = value;
            break
          case "0020": //加浓控制
            this.data.plusContral = value
            break
          case "0021": //稳定性调节
            this.data.adjust = value
            break
          case "0024":
            var state = parseInt(value, 16)
            if ((state & 0x0001) !== 0) { //定时停在工作
              this.data.reservation = "启用"
            }
            if ((state & 0x0002) !== 0) { //定时启在工作
              this.data.reservation = "启用"
            }

            break
          case "0025":
            this.data.totalTimeHour = value
            break
          case "0026":
            this.data.totalTimeMin = value
            break
        }
      }
    });

    var isNotNULL = (value) => {
      return !(value === null);
    }

    console.log(this.data.valtage)
    this.setData({
      'valtage': this.data.valtage,
      'objectArray[0].value': isNotNULL(this.data.speed) ? this.data.speed.toString() : "",
      'objectArray[1].value': isNotNULL(this.data.valtage) && isNotNULL(this.data.current) ? (this.data.valtage * this.data.current).toFixed(2) : "",
      'objectArray[2].value': isNotNULL(this.data.runHour) && isNotNULL(this.data.runMin) ? (this.data.runHour + '时' + this.data.runMin + '分') : "",
      'objectArray[3].value': isNotNULL(this.data.totalTimeHour) && isNotNULL(this.data.totalTimeMin) ? (this.data.totalTimeHour + '时' + this.data.totalTimeMin + '分') : "",
      'objectArray[4].value': isNotNULL(this.data.startValtage) ? this.data.startValtage.toString() : "",
      'objectArray[5].value': isNotNULL(this.data.plusContral) ? this.data.plusContral.toString() : "",
      'objectArray[6].value': isNotNULL(this.data.outValtage) ? this.data.outValtage.toString() : "",
      'objectArray[7].value': isNotNULL(this.data.adjust) ? this.data.adjust.toString() : "",
      'objectArray[8].value': this.data.machineMode,
      'objectArray[9].value': null, //控制器序列号
      'objectArray[10].value': this.data.machineVersion, //产品型号
      'objectArray[11].value': app.globalData.bluetoothName,
      'objectArray[12].value': cmd.getHomeFaceStatus(), //面板开关状态
      'objectArray[13].value': cmd.getMachineStatus() ? "正在运行" : "停止运行", //发电机运行状态
      'objectArray[14].value': "--", //激活日期
      'objectArray[15].value': "--", //激活地址
      'objectArray[16].value': "--", //激活用户
      'objectArray[17].value': this.data.reservation, //预约启停
      'objectArray[18].value': isNotNULL(this.data.startTimeHour) ? this.data.startTimeHour.toString() + ":" + this.data.startTimeMin.toString() : "", //启动时间
      'objectArray[19].value': isNotNULL(this.data.stopTimeHour) ? this.data.stopTimeHour.toString() + ":" + this.data.stopTimeMin.toString() : "", //停止时间
      'objectArray[20].value': isNotNULL(this.data.machineTemperature) ? this.data.machineTemperature.toString() : "",
      'objectArray[21].value': isNotNULL(this.data.controllerTemperature) ? this.data.controllerTemperature.toString() : "",
    })

  }
})